package common

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"path"
	"path/filepath"
	"server/global"
	model2 "server/internal/model"
	"server/internal/pkg/response"
	"server/utils/tools"
	"strconv"
	"strings"
	"time"
)

var Common = new(common)

type common struct{}
type List struct {
	Label string `json:"label" gorm:"column:name"`
	Value int    `json:"value" gorm:"column:id"`
}

// Router 路由
func (a common) Router(r *gin.RouterGroup) {

	r.POST("/upload", a.upload) //单文件上传
	r.GET("/area", a.area)
}

func (common) area(ctx *gin.Context) {
	Db := global.GL_DB
	province := ctx.Query("province")
	city := ctx.Query("city")
	pid := "0"
	if province != "" {
		pid = province
	}
	if city != "" {
		pid = city
	}

	table := model2.Area{}
	var list []List
	Db.Model(&table).Where("pid = ?", pid).Find(&list)
	ctx.JSON(200, gin.H{"code": 0, "msg": "ok", "data": list})
}

func (common) upload(ctx *gin.Context) {
	// 获取文件(注意这个地方的file要和html模板中的name一致)
	file, err := ctx.FormFile("file")
	if err != nil {
		//fmt.Println("获取数据失败")
		response.Error(ctx, "", err.Error())

		return
	} else {
		//获取文件名称
		//fmt.Println(file.Filename)

		//文件大小
		//fmt.Println(file.Size)
		var size = int64(global.GL_CONFIG.File.Size) //文件大小限制 MB
		if file.Size/1024/1024 > size {
			response.Error(ctx, "图片大小不能超过"+strconv.Itoa(global.GL_CONFIG.File.Size)+"MB")
			return
		}
		//获取文件的后缀名
		extString := path.Ext(file.Filename)
		//fmt.Println(extstring)
		//根据当前时间鹾生成一个新的文件名
		fileNameInt := time.Now().Unix()
		fileName := strings.Split(file.Filename, extString)[0] + strconv.FormatInt(fileNameInt, 10) + extString

		//保存上传文件
		filePath := filepath.Join(tools.Mkdir("public/upload"), "/", fileName)
		err = ctx.SaveUploadedFile(file, filePath)
		if err != nil {
			response.Error(ctx, "", err.Error())
			return
		}

		filePath = strings.Replace(filePath, string(filepath.Separator), "/", -1)
		// 获取文件后缀
		//fileExt := filepath.Ext(file.Filename)
		//if fileExt == ".mp4" {
		//	ffm.TakeVideoFirstFrame(filePath)
		//}
		response.Success(ctx, filePath, "文件上传成功")
	}
}

func isContains(s []string) bool {
	for _, v := range s {
		//json转map
		maps := make(map[string]interface{})
		json.Unmarshal([]byte(v), &maps)
		var field string
		field = maps["field"].(string)
		if field == "contains" {
			if maps["val"].(string) == "1" {
				return true
			} else {
				return false
			}
			break
		}

	}
	return false
}
